//
//  JAChannelView.m
//  网易新闻
//
//  Created by Arvin on 17/3/18.
//  Copyright © 2017年 Arvin. All rights reserved.
//

#import "JAChannelView.h"
#import "JAChannelModel.h"
#import "JAChannelLable.h"
#import "CZAdditions.h"

const int baseTag = 555;

@implementation JAChannelView

-(id)initWithFrame:(CGRect)frame{
    
    if(self = [super initWithFrame:frame])
    {
        
        self.backgroundColor = [UIColor whiteColor];
        //初始化
        _channelModelArr = [JAChannelModel channelModelArr];
        
        [self setupUI];
    }
    
    return self;
}

-(void)setupUI{
    
    self.showsHorizontalScrollIndicator = NO;
    CGFloat origin = 0;
    NSInteger index = 0;
    for (JAChannelModel *model in _channelModelArr) {
        JAChannelLable *lable = [JAChannelLable lableWithModel:model];
        CGRect frame = CGRectMake(origin, 0, lable.bounds.size.width, 40);
        lable.frame = frame;
        
        origin += lable.bounds.size.width;
        
        [self addSubview:lable];
        
        //设置默认不被选中
        lable.isSelected = NO;
        
        //给lable设置一个tag
        lable.tag = baseTag + index;
        
        //给lable添加点击事件
        lable.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changeSelectedIndex:)];
        [lable addGestureRecognizer:tap];
        
        index += 1;
    }
    
    //将第一个lable设为高亮
    self.selectedIndex = 0;
    
    self.contentSize = CGSizeMake(origin, 40);
    
}

//点击事件
//改变选中的Lable
-(void)changeSelectedIndex:(UITapGestureRecognizer *)tap{
    
    //获取到被点击的lable,和它的index
    JAChannelLable *lable = (JAChannelLable *)tap.view;
    NSInteger index = lable.tag - baseTag;
    
    //设置当前选中的index,当改变了setSelectedIndex的值时,可以同时改变对应的lable的选中状态
    [self setSelectedIndex:index];
    
    //让代理切换频道
    if(_channelDelegate && [_channelDelegate respondsToSelector:@selector(channelChanged:)])
    {
        [self.channelDelegate channelChanged:index];
    }
    
}


-(void)setSelectedIndex:(NSInteger)selectedIndex{
    
    //对应的lable应该取消选中状态
    JAChannelLable *selectedLable = [self viewWithTag:_selectedIndex + baseTag];
    selectedLable.isSelected = NO;
    
    //selectedIndex //对应的label应该设为选中状态
    JAChannelLable *shouldSelectedLable = [self viewWithTag:selectedIndex + baseTag];
    shouldSelectedLable.isSelected = YES;
    
    //解决将要被高度的label超过屏幕的bug
    CGFloat originX = shouldSelectedLable.frame.origin.x;
    CGFloat rightX = shouldSelectedLable.frame.origin.x + shouldSelectedLable.frame.size.width;
    
    if(originX < self.contentOffset.x || rightX >self.contentOffset.x)
    {
        [self scrollRectToVisible:shouldSelectedLable.frame animated:YES];
    }
    
    _selectedIndex = selectedIndex;
}

@end
